package com.ruoyi.system.util;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class WorkbookExportUtil {
    public int sheetIndex = 0;
    private static final Logger log = LoggerFactory.getLogger(ExcelUtil2.class);

    private List<ExcelUtil2Element> sheets;
    private Workbook wb;
    private String fileName;

    public WorkbookExportUtil() {
    }

    public WorkbookExportUtil(Workbook wb, String fileName) {
        this.wb = wb;
        this.fileName = fileName;
    }

    public AjaxResult exportExcel() {
        OutputStream out = null;
        try {

            String filename = ExcelUtil.encodingFilename(fileName);
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            return AjaxResult.success(filename);
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new BusinessException("导出Excel失败，请联系网站管理员！");
        } finally {
            if (wb != null) {
                try {
                    wb.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }

    public List<ExcelUtil2Element> getSheets() {
        return sheets;
    }


    public Workbook getWb() {
        return wb;
    }

}
